package logic

import (
	"context"
	"errors"
	"shop_srv/cache"
	"shop_srv/models"

	"shop_srv/internal/svc"
	"shop_srv/shop"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shop.LoginRequest) (*shop.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var u models.User
	var err error

	if in.Account == "" {
		if in.Mobile == "" {
			logx.Error("手机号不能为空")
			return nil, errors.New("手机号不能为空")
		}
		if err = u.GetUserByMobile(in.Mobile); err != nil {
			logx.Error("用户信息获取失败")
			return nil, errors.New("用户信息获取失败")
		}
		if u.ID == 0 {
			logx.Error("该用户未注册")
			return nil, errors.New("该用户未注册")
		}
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if result != in.SmsCode {
			logx.Error("短信验证码错误")
			return nil, errors.New("短信验证码错误")
		}
	} else {
		if err = u.GetUserByAccount(in.Account); err != nil {
			logx.Error("用户信息获取失败")
			return nil, errors.New("用户信息获取失败")
		}
		if u.ID == 0 {
			logx.Error("该账户无效！")
			return nil, errors.New("该账户无效！")
		}
		if in.Password != u.Password {
			logx.Error("密码错误")
			return nil, errors.New("密码错误")
		}
	}

	return &shop.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
